package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.WareForm;
import ru.housewife.model.Ware;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class SearchWares implements HibernateAction<List<WareForm>> {

    private CacheManager cacheManager = CacheManager.getInstance();

    private String name;

    private int offset;

    private int maxCount;

    public SearchWares(String name, int offset, int maxCount) {
        this.name = name;
        this.offset = offset;
        this.maxCount = maxCount;
    }

    @Override
    public List<WareForm> execute(Session session) {
        Query q = session.createQuery("select w from Ware w where lower(w.name) like :nameFilter");
        q.setString("nameFilter", name.toLowerCase() + '%');
        q.setFirstResult(offset);
        q.setMaxResults(maxCount);
        List<Ware> lst = q.list();
        List<WareForm> result = new ArrayList<WareForm>(lst.size());
        for (Ware ware : lst) {
            WareForm wareForm = cacheManager.getWareForm(ware.getId());
            if (wareForm != null) {
                result.add(wareForm);
            }
        }
        return result;
    }
}
